import { useLayoutEffect, useState } from 'react'

export function useTheme() {
  const [isDark, setIsDark] = useState(false)
  const schemeAttr = 'data-prefers-color-scheme'

  function setColorScheme(scheme: 'dark' | 'light') {
    document.documentElement.setAttribute(schemeAttr, scheme)
    document.documentElement.classList.remove(isDark ? 'dark' : 'light')
    document.documentElement.classList.add(scheme)
  }

  function toggleDark() {
    setColorScheme(isDark ? 'light' : 'dark')
    setIsDark(!isDark)
  }

  useLayoutEffect(() => {
    const isBrowserDark =
      window.matchMedia &&
      window.matchMedia('(prefers-color-scheme: dark)').matches

    if (isBrowserDark) {
      setColorScheme('dark')
      setIsDark(true)
    } else {
      setColorScheme('light')
      setIsDark(false)
    }
  }, [])

  return {
    isDark,
    toggleDark
  }
}
